/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-13 Time: 22:23
 *
 * 我的工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    TouchableOpacity,
    ScrollView, Platform, BackHandler,
} from 'react-native';
import {connect} from 'react-redux';
import {COLOR_THEME, COLOR_WHITE, FONT_COLOR_SUB_TITLE} from "../../../constant/PHColors"
import {styles} from './ShowOrderDetailScreen.Style'
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import AntDesign from "react-native-vector-icons/AntDesign";
import {SCREEN_HEIGHT, SCREEN_WIDTH} from "../../../constant/PHScreen";
import {Header} from "react-navigation";
import {onRetrieveOrderDetail, retrieveOrder_Detail} from "./Actions";

class ShowOrderDetailScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: navigation.getParam('ordertype'),
        headerRight: (
            <TouchableOpacity activeOpacity={0.9} onPress={navigation.getParam('addClick')}>
                <View style={{width: 80, height: 44, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
                    <AntDesign name={'plus'} size={25} style={{color: '#212121', marginLeft: 10,fontWeight: 'bold'}}/>
                </View>
            </TouchableOpacity>
        )
    });

    // 构造
    constructor(props) {
        super(props);

        // 初始状态
        this.state = {
            room: this.props.navigation.getParam("room"),
            ordertype: this.props.navigation.getParam("ordertype"),
            datasource:{},      //数据源
        };

    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        if (nextProps.onRetrieveOrderDetail !== this.props.onRetrieveOrderDetail && nextProps.onRetrieveOrderDetail.fetchStatus === FetchStatus.Success) {
            if (nextProps.onRetrieveOrderDetail.RETURN === ReturnStatus.Success) {
                let datasource = {};
                nextProps.onRetrieveOrderDetail.whsk_Order_DetailBy.map((item,value)=>{
                    if(datasource[item.orderid]){
                        datasource[item.orderid].push(item)
                    }else{
                        datasource[item.orderid]=[item]
                    }
                })

                this.setState({
                    datasource:datasource,
                })
            } else {
                // dispatch(doDisplayWarnMessage(nextProps.onRetrieveOrderDetail.MSG))
            }
        }
    }

    // 组件渲染后调用
    componentDidMount() {
        let {dispatch} = this.props;

        let str = {"arg":{"ordertype":this.state.ordertype,"room":this.state.room}}
        dispatch(retrieveOrder_Detail(JSON.stringify(str)))
    }

    componentWillMount() {
        this.props.navigation.setParams({addClick: this.add_button,ordertype: this.state.ordertype});
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    componentWillUnmount() {
        if (Platform.OS === 'android'||Platform.OS==='ios') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
    };

    onBackAndroid = () =>{
        if(this.props.navigation.isFocused()){//判断   该页面是否处于聚焦状态
            this.props.navigation.state.params.callBack();
        }
    };


    render() {
        return (
            <SafeAreaView style={styles.body}>

                <View style={[styles.body, {paddingBottom: 50}]}>
                    <ScrollView style={styles.scrollView}>
                        {
                            this.state.datasource.length === 0
                                ?
                                (
                                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                        if(this.state.ordertype==="查房,查遗留/异常/消费"){
                                            this.props.navigation.navigate('addCheckUnusualScreen',{place:this.state.room,callBack:()=>this.freshScreen()});
                                        }else if(this.state.ordertype==="布草/易耗品/酒水补充"){
                                            this.props.navigation.navigate('addLinenAndBarScreen',{place:this.state.room,callBack:()=>this.freshScreen()});
                                        }
                                    }}>
                                        <View style={{marginTop:10,marginRight: 15 ,flexDirection: 'column',alignItems: 'center',justifyContent: 'center',height:SCREEN_HEIGHT-Header.HEIGHT-40}}>
                                            <Text style={styles.text}>
                                                当前暂无记录,点击新建
                                            </Text>
                                        </View>
                                    </TouchableOpacity>
                                )
                                :
                                (
                                    this._render_result()
                                )
                        }
                    </ScrollView>
                </View>

                <View style={styles.bodyBottom}>
                    <TouchableOpacity activeOpacity={0.8} onPress={() => this.add_button()}>
                        <View style={styles.bodyBottomRight}>
                            <Text style={styles.cellTitleText}>
                                点击继续添加
                            </Text>
                        </View>
                    </TouchableOpacity>
                </View>

            </SafeAreaView>
        )
    }

    _render_result=()=>{
        let outHtml = []

        for (let val in this.state.datasource){
            let value = this.state.datasource[val];
            let html = (
                <View style={[styles.container,{marginTop:20}]}>
                    <View style={styles.orderTop}>
                        <View style={styles.iconBox}>
                            <AntDesign name={'clockcircleo'} size={20} style={{color: '#6ba1f9'}}/>
                        </View>
                        <View style={styles.textBox}>
                            <View style={styles.leftBox}>
                                <Text style={[styles.titleText,{marginLeft:5}]}>
                                    {value[0].crdate}
                                </Text>
                                <Text style={[styles.text,{color:'#6b6b6b',marginLeft:2,marginTop:3}]}>
                                    （GNO：{value[0].gno}）
                                </Text>
                            </View>
                        </View>
                        <View style={styles.arrowBox}>
                            <Text style={[styles.text,{marginTop:3}]}>
                                {value[0].log_user}
                            </Text>
                        </View>
                    </View>
                    <View style={styles.orderCenter}>
                        {
                            this.get_info('消费项目','消费',value)
                        }
                        {
                            this.get_info('遗留','遗留',value)
                        }
                        {
                            this.get_info('客房状态','备注',value)
                        }
                        {
                            this.get_info('布草','布草',value)
                        }
                        {
                            this.get_info('易耗品','易耗品',value)
                        }
                    </View>
                </View>
            );
            outHtml.push(html)
        }

        return outHtml

    };

    //下一步
    add_button=()=>{
        if(this.state.ordertype==="查房,查遗留/异常/消费"){
            this.props.navigation.navigate('addCheckUnusualScreen',{place:this.state.room,callBack:()=>this.freshScreen()});
        }else if(this.state.ordertype==="布草/易耗品/酒水补充"){
            this.props.navigation.navigate('addLinenAndBarScreen',{place:this.state.room,callBack:()=>this.freshScreen()});
        }
    };

    freshScreen=()=>{
        let {dispatch} = this.props;
        this.props.navigation.navigate('ShowOrderDetailScreen');

        let str = {"arg":{"ordertype":this.state.ordertype,"room":this.state.room}};
        dispatch(retrieveOrder_Detail(JSON.stringify(str)))
    };

    get_info=(type,name,datesource)=>{
        let outHtml;
        let detailHtml = this.get_info_detail(type,datesource);
        if(detailHtml.length>0){
            outHtml = (
                <View style={styles.orderCenterLine}>
                    <View style={styles.orderCenterLeft}>
                        <Text style={styles.orderCenterText}>
                            {name}：
                        </Text>
                    </View>
                    <View style={styles.orderCenterRight}>
                        {
                            detailHtml
                        }
                    </View>
                </View>
            )
        }else{
            outHtml = (
                <View>

                </View>
            );
        }
        return outHtml
    }

    get_info_detail=(type,datesource)=>{
        let htmlArr=[];
        datesource.map((item, index) => {
            if(type===item.codetype){
                let html;
                html = (
                    <View style={{width:SCREEN_WIDTH * 2/3-30}}>
                        <Text style={styles.orderCenterText}>
                            {item.info_detail}
                        </Text>
                    </View>
                )
                htmlArr.push(html)
            }
        })
        return htmlArr
    }
}

const props = state => {
    return {
        onRetrieveOrderDetail:state.onRetrieveOrderDetail
    }
}

export default ShowOrderDetailScreen = connect(props)(ShowOrderDetailScreen);